package cn.seaboot.admin.file.web;

import cn.seaboot.admin.upload.OutputInfo;
import cn.seaboot.admin.upload.Uploader;
import cn.seaboot.commons.file.FilenameUtils;
import cn.seaboot.commons.file.ResponseWriter;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * 此接口所有数据不经过数据库持久化，
 * 因此，可能会产生大量的垃圾数据，如果你希望通过平台管理，建议保存文件信息，
 * 经过数据库持久化的代码，参考{@link FileCtrl}
 *
 * @author Mr.css
 * @version 2020-01-08 16:12
 */
@Controller
@Tag(name = "文件磁盘管理")
@RequestMapping(value = "/sys/disk")
public class FileUploadCtrl {

    /**
     * 文件上传，未经过数据持久化
     *
     * @param type 文件类型，与存储路径相关
     * @param file 文件实体对象
     * @return 文件存储信息
     */
    @Operation(description = "文件预览")
    @ResponseBody
    @RequestMapping(value = "/upload/{type}", method = RequestMethod.POST)
    public OutputInfo upload(@PathVariable String type, @RequestParam MultipartFile file) throws IOException {
        return Uploader.storage(type).write(file);
    }

    /**
     * 文件预览
     *
     * @param type     文件类型
     * @param path     存储路径(包含文件名)
     * @param response -
     */
    @Operation(description = "文件预览")
    @Parameters({
            @Parameter(name = "type", description = "文件类型"),
            @Parameter(name = "path", description = "文件相对路径")})
    @RequestMapping(value = "/preview/{type}", method = RequestMethod.GET)
    public void preview(@PathVariable String type, @RequestParam String path
            , HttpServletResponse response) throws IOException {
        String downName = FilenameUtils.getName(path);
        Uploader localFile = Uploader.storage(type);
        try (InputStream inputStream = localFile.openInputStream(path)) {
            ResponseWriter.download(response, inputStream, downName);
        }
    }

    /**
     * 文件下载
     *
     * @param type     文件类型
     * @param path     存储路径(包含文件名)
     * @param response -
     * @throws IOException -
     */
    @Operation(description = "文件下载")
    @Parameters({
            @Parameter(name = "path", description = "文件相对路径")})
    @RequestMapping(value = "/download/{type}", method = RequestMethod.GET)
    public void download(@PathVariable String type, @RequestParam String path
            , HttpServletResponse response) throws IOException {
        String downName = FilenameUtils.getName(path);
        Uploader localFile = Uploader.storage(type);
        try (InputStream inputStream = localFile.openInputStream(path)) {
            ResponseWriter.download(response, inputStream, downName);
        }
    }
}
